package modules.fin.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import luxing.common.controller.BaseController;
import luxing.exception.BusinessException;
import luxing.hibernate.CriteriaQuery;
import luxing.util.CriteriaQueryUtil;
import luxing.util.LoginUserUtil;
import luxing.util.ValidatorUtil;
import luxing.web.model.DataGrid;
import luxing.web.model.Result;
import modules.fin.entity.Expenses;
import modules.fin.entity.OutlayUnit;
import modules.fin.entity.OutlayUnitSum;
import modules.fin.service.ExpensesService;
import modules.fin.service.OutlayUnitService;
import modules.sys.entity.Dict;
import modules.sys.entity.Log;
import modules.sys.service.DictService;
import modules.sys.service.LogService;

/**
 * 
 * @author zzc
 *
 */
@Controller
@RequestMapping("/outlayUnitController")
public class OutlayUnitController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(OutlayUnitController.class);

	@Autowired
	private LogService logService;
	@Autowired
	private OutlayUnitService outlayUnitService;
	@Autowired
	private ExpensesService expensesService;
	@Autowired
	private DictService dictService;

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "index")
	public ModelAndView index(HttpServletRequest request) {
		List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_OUTLAY_UNIT,
				Expenses.STATUS_ENABLE);
		request.setAttribute("expensesList", expensesList);
		return new ModelAndView("modules/fin/outlayUnit-list");
	}

	/**
	 * 列表数据
	 * 
	 * @param outlayUnit
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "list")
	public void list(OutlayUnit outlayUnit, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(OutlayUnit.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, outlayUnit, request.getParameterMap());
			// 费用类型
			String exs = request.getParameter("exs");
			if (StringUtils.isNotBlank(exs)) {
				cq.eq("expenses.id", exs);
			}
			cq.add();
			outlayUnitService.listByPage(cq, true);
			dataGrid.setFooter("amount,vehicle.sn:合计");
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("付单位款查询失败", e);
			throw new BusinessException("付单位款查询失败", e);
		}
	}

	/**
	 * 增加页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(HttpServletRequest req) {
		List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_OUTLAY_UNIT,
				Expenses.STATUS_ENABLE);
		req.setAttribute("expensesList", expensesList);
		return new ModelAndView("modules/fin/outlayUnit-add");
	}

	/**
	 * 修改页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(OutlayUnit outlayUnit, HttpServletRequest req) {
		if (StringUtils.isNotBlank(outlayUnit.getId())) {
			outlayUnit = outlayUnitService.get(OutlayUnit.class, outlayUnit.getId());
			req.setAttribute("outlayUnitPage", outlayUnit);
			List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_OUTLAY_UNIT,
					Expenses.STATUS_ENABLE);
			req.setAttribute("expensesList", expensesList);
		}
		return new ModelAndView("modules/fin/outlayUnit-update");
	}

	/**
	 * 往来单位核销页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUnitSettle")
	public ModelAndView goUnitSettle(HttpServletRequest req) {
		List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_OUTLAY_UNIT,
				Expenses.STATUS_ENABLE);
		req.setAttribute("expensesList", expensesList);
		return new ModelAndView("modules/fin/outlayUnit-settle");
	}

	/**
	 * 车辆核销页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goVehicleSettle")
	public ModelAndView goVehicleSettle(OutlayUnit outlayUnit, HttpServletRequest req) {
		if (StringUtils.isNotBlank(outlayUnit.getId())) {
			outlayUnit = outlayUnitService.get(OutlayUnit.class, outlayUnit.getId());
			req.setAttribute("outlayUnitPage", outlayUnit);
			List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_OUTLAY_UNIT,
					Expenses.STATUS_ENABLE);
			req.setAttribute("expensesList", expensesList);
		}
		return new ModelAndView("modules/fin/outlayUnitVehicle-settle");
	}

	/**
	 * 查看页面
	 * 
	 * @param outlayUnit
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "goDetail")
	public ModelAndView goDetail(OutlayUnit outlayUnit, HttpServletRequest request) {
		if (StringUtils.isNotBlank(outlayUnit.getId())) {
			outlayUnit = outlayUnitService.get(OutlayUnit.class, outlayUnit.getId());
			request.setAttribute("outlayUnitPage", outlayUnit);
			List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_OUTLAY_UNIT,
					Expenses.STATUS_ENABLE);
			request.setAttribute("expensesList", expensesList);
		}
		return new ModelAndView("modules/fin/outlayUnit-detail");
	}

	/**
	 * 车辆明细tab
	 * 
	 * @return
	 */
	@RequestMapping(params = "tab")
	public ModelAndView tab(HttpServletRequest req) {
		return new ModelAndView("modules/fin/outlayUnit-tab");
	}

	/**
	 * 往来单位核销明细
	 * 
	 * @return
	 */
	@RequestMapping(params = "unitSettleTab")
	public ModelAndView unitSettleTab(HttpServletRequest req) {
		// 获取往来单位
		String unit = req.getParameter("unit");
		if (StringUtils.isBlank(unit)) {
			List<Dict> dictList = dictService.listByGroupCode("unit", LoginUserUtil.getLoginUser().getTenantId());
			if (CollectionUtils.isNotEmpty(dictList)) {
				unit = dictList.get(0).getId();
			}
		}
		// 获取费用
		String expensesId = req.getParameter("expensesId");
		if (StringUtils.isBlank(expensesId)) {
			List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_OUTLAY_UNIT,
					Expenses.STATUS_ENABLE);
			if (CollectionUtils.isNotEmpty(expensesList)) {
				expensesId = expensesList.get(0).getId();
			}
		}
		List<OutlayUnit> outlayUnitList = outlayUnitService.listByUnitAndExpensesAndStatus(unit, expensesId,
				OutlayUnit.STATUS_NO);
		BigDecimal totalAmount = new BigDecimal(0);
		for (OutlayUnit outlayUnit : outlayUnitList) {
			totalAmount = totalAmount.add(outlayUnit.getAmount());
		}
		req.setAttribute("totalAmount", totalAmount);
		req.setAttribute("outlayUnitList", outlayUnitList);
		return new ModelAndView("modules/fin/outlayUnitSettle-tab");
	}

	/**
	 * 新增
	 * 
	 * @param outlayUnit
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public Result doAdd(OutlayUnit outlayUnit, HttpServletRequest request) {
		String msg = null;
		try {
			if (CollectionUtils.isNotEmpty(outlayUnit.getOutlayUnitList())) {
				for (OutlayUnit entity : outlayUnit.getOutlayUnitList()) {
					entity.setUnit(outlayUnit.getUnit());
					entity.setExpenses(outlayUnit.getExpenses());
					entity.setStatus(OutlayUnit.STATUS_NO);
				}
				outlayUnitService.batchSave(outlayUnit.getOutlayUnitList());
			}
			msg = "付单位款登记成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_ADD);
		} catch (Exception e) {
			msg = "付单位款登记失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 修改
	 * 
	 * @param outlayUnit
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public Result doUpdate(OutlayUnit outlayUnit, HttpServletRequest request) {
		String msg = null;
		try {
			outlayUnitService.saveOrUpdate(outlayUnit);
			msg = "付单位款修改成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "付单位款修改失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public Result doDel(OutlayUnit outlayUnit, HttpServletRequest request) {
		String msg = null;
		try {
			outlayUnit = outlayUnitService.get(OutlayUnit.class, outlayUnit.getId());
			outlayUnitService.delete(outlayUnit);
			msg = "付单位款删除成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_DEL);
		} catch (Exception e) {
			msg = "付单位款删除失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 往来单位核销
	 * 
	 * @param outlayUnitSum
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doUnitSettle")
	@ResponseBody
	public Result doUnitSettle(OutlayUnitSum outlayUnitSum, HttpServletRequest request) {
		String msg = null;
		try {
			if (CollectionUtils.isNotEmpty(outlayUnitSum.getOutlayUnitList())) {
				// 编号
				String sn = outlayUnitService.getSn();
				outlayUnitSum.setSn(sn);
				// 状态
				outlayUnitSum.setStatus(OutlayUnitSum.STATUS_ENABLE);
				// 核销金额
				BigDecimal totalAmount = new BigDecimal(0);
				Iterator<OutlayUnit> iterator = outlayUnitSum.getOutlayUnitList().iterator();
				while (iterator.hasNext()) {
					OutlayUnit outlayUnit = iterator.next();
					if (StringUtils.equals(outlayUnit.getStatus(), OutlayUnit.STATUS_YES)) {
						totalAmount = totalAmount.add(outlayUnit.getAmount());
						outlayUnitSum.setExpenses(outlayUnit.getExpenses());
						outlayUnit.setSettleBy(LoginUserUtil.getUser().getName());
						outlayUnit.setSettleDate(new Date());
					} else {
						iterator.remove();
					}
				}
				outlayUnitSum.setAmount(totalAmount);
				// bean校验
				msg = ValidatorUtil.validate(outlayUnitSum);
				if (StringUtils.isNotBlank(msg)) {
					return Result.error(msg);
				}
				outlayUnitService.settle(outlayUnitSum);
				msg = "付单位款核销成功";
				logger.info(msg);
				logService.addLogInfo(msg, Log.OPERATE_ADD);
			}
		} catch (Exception e) {
			msg = "付单位款核销失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 车辆核销
	 * 
	 * @param outlayUnit
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doVehicleSettle")
	@ResponseBody
	public Result doVehicleSettle(OutlayUnit outlayUnit, HttpServletRequest request) {
		String msg = null;
		try {
			List<OutlayUnit> outlayUnitList = new ArrayList<OutlayUnit>();
			outlayUnit.setStatus(OutlayUnit.STATUS_YES);
			outlayUnit.setCreateBy(LoginUserUtil.getUser().getName());
			outlayUnit.setCreateDate(new Date());
			outlayUnitList.add(outlayUnit);
			// 付款记录
			OutlayUnitSum outlayUnitSum = new OutlayUnitSum();
			String sn = outlayUnitService.getSn();
			outlayUnitSum.setSn(sn);
			outlayUnitSum.setUnit(outlayUnit.getUnit());
			outlayUnitSum.setExpenses(outlayUnit.getExpenses());
			outlayUnitSum.setAmount(outlayUnit.getAmount());
			String way = request.getParameter("way");
			outlayUnitSum.setWay(way);
			outlayUnitSum.setStatus(OutlayUnitSum.STATUS_ENABLE);
			outlayUnitSum.setOutlayUnitList(outlayUnitList);

			outlayUnitService.settle(outlayUnitSum);
			msg = "付单位款核销成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "付单位款核销失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

}
